//
//  subView1ForGetJobSheet.m
//  HondaPro_2
//
//  Created by Eric on 13-6-20.
//  Copyright (c) 2013年 glendale. All rights reserved.
//

#import "subView1ForGetJobSheet.h"
#import "UserDefinedCellForSubView1ForGetJobSheet.h"

@interface subView1ForGetJobSheet ()<UIAlertViewDelegate>
/** 收费区分列表 */
@property(nonatomic,strong)NSMutableDictionary *chargeDiff;
//创建控件
-(void)createStaticLabels;
-(void)createTableView;



@end

@implementation subView1ForGetJobSheet

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        
        [self createStaticLabels];
        [self createTableView];
    }
    return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    
    [self freshenViewDis];
}

#pragma mark - 创建控件

-(void)createStaticLabels
{
    //,@"DISCOUNT":  @"bottomLbl",
    NSArray *arrForAllKeys = [NSArray arrayWithObjects:
                              @"CHARGE_PARTITION_CODE",
                              @"LABOUR_CODE",
                              @"LABOUR_NAME",
                              @"STD_LABOUR_HOUR",
                              @"LABOUR_PRICE",
                              @"LABOUR_AMOUNT",nil];

    
    
//    NSDictionary *dicForStaticLabelsRect = [NSDictionary dictionaryWithObjectsAndKeys:
//                                            [NSValue valueWithCGRect:CGRectMake(0, 0, self.frame.size.width, 51)],@"bottomLbl",
//                                            [NSValue valueWithCGRect:CGRectMake(0, 0, 70, 50)],@"CHARGE_PARTITION_CODE",
//                                            [NSValue valueWithCGRect:CGRectMake(71, 0, 210, 50)],@"LABOUR_CODE",
//                                            [NSValue valueWithCGRect:CGRectMake(281, 0, 300, 50)],@"LABOUR_NAME",
//                                            [NSValue valueWithCGRect:CGRectMake(581, 0, 100, 50)],@"STD_LABOUR_HOUR",
//                                            [NSValue valueWithCGRect:CGRectMake(681, 0, 100, 50)],@"LABOUR_PRICE",
//                                            [NSValue valueWithCGRect:CGRectMake(781, 0, 100, 50)],@"LABOUR_AMOUNT",
//                                            [NSValue valueWithCGRect:CGRectMake(881, 0, 50, 50)],@"DISCOUNT",nil];
    
    //,
    //    @"折扣",@"DISCOUNT" @""@"bottomLbl",
    NSDictionary *dicForStaticLabelsText = [NSDictionary dictionaryWithObjectsAndKeys:
                                           
                                            @"收费区分",@"CHARGE_PARTITION_CODE",
                                            @"维修项目代码",@"LABOUR_CODE",
                                            @"维修项目名称",@"LABOUR_NAME",
                                            @"标准工时",@"STD_LABOUR_HOUR",
                                            @"工时单价",@"LABOUR_PRICE",
                                            @"工时费",@"LABOUR_AMOUNT",nil];
    
    CGFloat w=self.bounds.size.width/arrForAllKeys.count;
    for (int i = 0; i<[arrForAllKeys count]; i++)
    {
        NSString *strKeys = [arrForAllKeys objectAtIndex:i];
       
        UILabel *lbl = [[UILabel alloc] init];
        lbl.frame =CGRectMake(i*w, 0, w, 50);
        lbl.textAlignment=NSTextAlignmentCenter;
        if ([strKeys isEqualToString:@"bottomLbl"])
        {
            //以灰色为标题label的背景打底色
//            lbl.backgroundColor = [UIColor grayColor];
            //将灰色背景色修改成浅灰色
            lbl.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
        }
        else
        {
            //以浅灰色为标题label的背景色
            lbl.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
//            lbl.backgroundColor = [UIColor redColor];
        }
        lbl.textColor = [UIColor grayColor];
        lbl.font = [UIFont fontWithName:@"ArialMT" size:16];
        lbl.text = [dicForStaticLabelsText objectForKey:strKeys];
        [self addSubview:lbl];
        
        lbl.numberOfLines = 2;
    }
}

-(void)createTableView
{
    tableViewDis = [[UITableView alloc] initWithFrame:CGRectMake(0, 51, self.frame.size.width, 168-21)];
    tableViewDis.backgroundColor = [UIColor clearColor];
    
    tableViewDis.dataSource = self;
    tableViewDis.delegate = self;
    
    [self addSubview:tableViewDis];
}

#pragma mark - 刷新数据

-(void)freshenViewDis
{
    [tableViewDis reloadData];
}

#pragma mark - tableView dataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    /*
     此处的操作是：
     （1）如果 陈述号\作业指示 的选择 至少有一个没有在数据行内，则不显示数据，否则，显示
     */
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    NSInteger nRowSum = modelIns.repairProjects.count;
    
    return 3+nRowSum;
}

//哪几行可以编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.canEdit) {
        MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
        
        if ([indexPath row]<modelIns.repairProjects.count)
        {
            return YES;
        }
    }    
    return NO;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    UserDefinedCellForSubView1ForGetJobSheet *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (nil == cell)
    {
        cell = [[UserDefinedCellForSubView1ForGetJobSheet alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
        
    //cell的风格是：浅浅灰色和浅灰色间隔出现，第一行是浅灰色
    NSInteger row = [indexPath row];
    switch (row%2)
    {
        case 0:
            //浅灰色
            cell.contentView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
            break;
        case 1:
            //浅浅灰色
            cell.contentView.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
            break;
            
        default:
            break;
    }
    
    
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    NSArray *arrRepairItemList = modelIns.repairProjects;
    if (row<[arrRepairItemList count])
    {
        NSDictionary *dicRepairItemList = [arrRepairItemList objectAtIndex:row];
        for (int i = 0; i<[cell.arrForAllLabelsKeysOnCell count]; i++)
        {
            NSString *strKey = [cell.arrForAllLabelsKeysOnCell objectAtIndex:i];
            id text = dicRepairItemList[strKey];
            //[strKey isEqualToString:@"STD_LABOUR_HOUR"]||[strKey isEqualToString:@"CLAIM_LABOUR"]
            if ([text isKindOfClass:[NSNumber class]]) {//如果是数字
                text = [text stringValue];
            }else if ([strKey isEqualToString:@"CHARGE_PARTITION_CODE"]){
                text = self.chargeDiff[dicRepairItemList[strKey]];
            }
            
            ((UILabel *)[cell.dicForAllLabelsOnCell objectForKey:[cell.arrForAllLabelsKeysOnCell objectAtIndex:i]]).text = text;
        }
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
    }
    else
    {
        for (int i = 0; i<[cell.arrForAllLabelsKeysOnCell count]; i++)
        {
            ((UILabel *)[cell.dicForAllLabelsOnCell objectForKey:[cell.arrForAllLabelsKeysOnCell objectAtIndex:i]]).text = @"";
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    return cell;
}

#pragma mark - tableView delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];
    
    //在此 将业务模型中对应的属性 设定为 当前选中的为第几行
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    if (row< modelIns.repairProjects.count) {
         modelIns.nRowForRepairItemList = row;
    }else{
         modelIns.nRowForRepairItemList = -1;
    }

}

#pragma mark - 出现删除按钮时，点击按钮时的操作

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    modelIns.nRowForRepairItemList = indexPath.row;
    NSDictionary * repairDic = modelIns.repairProjects[indexPath.row];
    if (repairDic[@"ACTIVITY_CODE"]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"与之相关的服务活动下的所有维修项目跟零件也将被删除，确定要删除吗" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.tag = 10000;
        [alert show];
    }else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"与之相关的零件也将被删除，确定删除吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
    }

    
}

-(NSMutableDictionary *)chargeDiff{
    if (_chargeDiff == nil) {
        _chargeDiff = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"TM_CHARGE_PARTITION"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            [_chargeDiff setObject:name forKey:val];
        }
    }
    return _chargeDiff;
}

-(NSMutableDictionary *)readershuDICimform
{
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path=[paths objectAtIndex:0];
    NSString *str=[path stringByAppendingPathComponent:@"Dic.text"];
    dic=[NSMutableDictionary dictionaryWithContentsOfFile:str];
    //nslog(@"%@",dic);
    return dic;
}

#pragma mark - UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    //确定
    if (alertView.tag == 10000) {
        if (buttonIndex == 1) {
            MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
            NSMutableDictionary *dic = modelIns.repairProjects[modelIns.nRowForRepairItemList];
            //删除服务活动
             [[NSNotificationCenter defaultCenter]postNotificationName:@"delActive" object:dic];
        }
    }else{
        if (buttonIndex == 1) {
            MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
            NSMutableDictionary *dic = modelIns.repairProjects[modelIns.nRowForRepairItemList];
            if (!dic[@"STATUS"]||[dic[@"STATUS"] isEqualToString:@"U"]) {//如果是存在数据库中的数据
                [dic setObject:@"D" forKey:@"STATUS"];
                [modelIns.deletedRepairProjects addObject:dic];
            }
            //移除项目
            [modelIns.repairProjects removeObjectAtIndex:modelIns.nRowForRepairItemList];
            
            NSString *projectCode = dic[@"LABOUR_CODE"];//维修项目代码
            NSString *pChargeCode = dic[@"CHARGE_PARTITION_CODE"];//收费区分
            //移除与之关联的零件
            for (int i = 0; i< modelIns.partList.count; i++) {
                NSDictionary *part = modelIns.partList[i];
                NSString *code = part[@"LABOUR_CODE"];//维修项目代码
                NSString *chargeCode = part[@"CHARGE_PARTITION_CODE"];//收费区分
                //如果维修项目和收费区分一致
                if ([projectCode isEqualToString:code] && [pChargeCode isEqualToString:chargeCode]) {
                    if (!dic[@"STATUS"]||[dic[@"STATUS"] isEqualToString:@"U"]) {//如果是存在数据库中的数据
                        [dic setObject:@"D" forKey:@"STATUS"];
                        [modelIns.deletedPartList addObject:dic];
                    }
                    [modelIns.partList removeObjectAtIndex:i];
                }
            }
            
            [self freshenViewDis];
            [[NSNotificationCenter defaultCenter]postNotificationName:REPAIR_ITEM_LIST_MSG_ object:nil];
        }
    }
   
}

@end
